// ============================================================================
// Account 实体定义
// ============================================================================

import {
  Entity,
  PrimaryColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  OneToMany,
  Index
} from 'typeorm'
import { Task } from './task.entity'
import { WeiboLoginData } from '@/shared/types'
import { WeiboLoginUserInfo } from '@roasmax/weibo-types'
/**
 * 微博扫码登录账号 用来做爬取数据的账号
 */
@Entity('accounts')
@Index(['id'], { unique: true })
@Index(['isValid'])
export class Account implements Partial<WeiboLoginUserInfo> {
  @PrimaryColumn({ type: 'bigint' })
  id: number;

  @Column({ unique: true, type: 'varchar', nullable: true })
  idstr: string;

  @Column({ type: 'int', default: 0, comment: 'PC新版本标识' })
  pc_new: number;

  @Column({ type: 'varchar', nullable: true })
  screen_name: string;

  @Column({ nullable: true, type: 'varchar' })
  profile_image_url?: string;

  @Column({ nullable: true, type: 'varchar' })
  profile_url?: string;

  @Column({ type: 'boolean', default: false })
  verified: boolean;

  @Column({ nullable: true, type: 'varchar' })
  domain?: string;

  @Column({ nullable: true, type: 'varchar' })
  weihao?: string;

  @Column({ nullable: true, type: 'varchar' })
  avatar_large?: string;

  @Column({ nullable: true, type: 'varchar' })
  avatar_hd?: string;

  @Column({ type: 'boolean', default: false })
  follow_me: boolean;

  @Column({ type: 'boolean', default: false })
  following: boolean;

  @Column({ type: 'int', default: 0 })
  mbrank: number;

  @Column({ type: 'int', default: 0 })
  mbtype: number;

  @Column({ type: 'int', default: 0 })
  v_plus: number;

  @Column({ type: 'int', default: 0 })
  user_ability: number;

  @Column({ type: 'boolean', default: false })
  planet_video: boolean;

  @Column({ nullable: true, type: 'varchar' })
  gender?: string;

  @Column({ nullable: true, type: 'varchar' })
  followers_count_str?: string;

  @Column({ nullable: true, type: 'varchar' })
  url?: string;

  @Column({ type: 'int', default: 0 })
  svip: number;

  @Column({ type: 'int', default: 0 })
  vvip: number;

  @Column({ nullable: true, type: 'varchar' })
  cover_image_phone?: string;

  @Column({ nullable: true, type: 'int' })
  type?: number;

  @Column({ nullable: true, type: 'int' })
  user_limit?: number;

  @Column({ type: 'json', nullable: true })
  icon_list?: any[];

  @Column({ type: 'json', nullable: true })
  watermark?: { markpos: number; nick: string; };

  @Column({ type: 'text' })
  cookies: string

  @Column({ name: 'is_valid', type: 'boolean', default: true })
  isValid: boolean

  @Column({ name: 'last_validated', type: 'datetime', nullable: true })
  lastValidated?: Date

  @Column({ name: 'login_method', nullable: true, type: 'varchar' })
  loginMethod?: string

  @Column({ name: 'followers_count', type: 'integer', nullable: true })
  followersCount?: number

  @Column({ name: 'following_count', type: 'integer', nullable: true })
  followingCount?: number

  @Column({ name: 'statuses_count', type: 'integer', nullable: true })
  statusesCount?: number

  @Column({ type: 'text', nullable: true })
  description?: string

  @Column({ nullable: true, type: 'varchar' })
  location?: string

  @Column({ name: 'verified_type', type: 'integer', nullable: true })
  verifiedType?: number

  @Column({ name: 'verified_reason', nullable: true, type: 'varchar' })
  verifiedReason?: string

  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date

  @UpdateDateColumn({ name: 'updated_at' })
  updatedAt: Date

  // 关系
  @OneToMany(() => Task, task => task.account, { cascade: true })
  tasks: Task[]

  /**
   * 转换为微博登录数据格式
   */
  toWeiboLoginData(): WeiboLoginData {
    const userInfo: WeiboLoginUserInfo = {
      id: this.id,
      idstr: this.idstr,
      pc_new: this.pc_new,
      screen_name: this.screen_name,
      profile_image_url: this.profile_image_url ?? '',
      profile_url: this.profile_url ?? '',
      verified: this.verified,
      verified_type: this.verifiedType ?? 0,
      domain: this.domain ?? '',
      weihao: this.weihao ?? '',
      avatar_large: this.avatar_large ?? '',
      avatar_hd: this.avatar_hd ?? '',
      follow_me: this.follow_me,
      following: this.following,
      mbrank: this.mbrank,
      mbtype: this.mbtype,
      v_plus: this.v_plus,
      user_ability: this.user_ability,
      planet_video: this.planet_video,
      description: this.description ?? '',
      location: this.location ?? '',
      gender: this.gender ?? 'n',
      followers_count: this.followersCount ?? 0,
      followers_count_str: this.followers_count_str ?? '',
      friends_count: this.followingCount ?? 0,
      statuses_count: this.statusesCount ?? 0,
      url: this.url ?? '',
      svip: this.svip,
      vvip: this.vvip,
      cover_image_phone: this.cover_image_phone ?? '',
      type: this.type ?? 0,
      user_limit: this.user_limit ?? 0,
      icon_list: this.icon_list ?? [],
      watermark: this.watermark ?? { markpos: 0, nick: '' },
      status_total_counter: {
        total_cnt_format: 0,
        comment_cnt: '',
        repost_cnt: '',
        like_cnt: '',
        total_cnt: '',
      },
    };
    return {
      id: this.id,
      cookies: JSON.parse(this.cookies),
      userInfo,
      timestamp: this.createdAt instanceof Date ? this.createdAt.getTime() : new Date(this.createdAt).getTime(),
      isValid: this.isValid,
      lastValidated: this.lastValidated,
      loginMethod: this.loginMethod as 'manual' | 'auto'
    }
  }

  /**
   * 从微博登录数据创建账号实体
   */
  static fromWeiboLoginData(data: WeiboLoginData): Account {
    const account = new Account();
    Object.assign(account, data.userInfo);
    account.id = data.id;
    account.cookies = JSON.stringify(data.cookies);
    account.isValid = data.isValid;
    account.lastValidated = data.lastValidated ? new Date(data.lastValidated) : undefined;
    account.loginMethod = data.loginMethod;
    account.followersCount = data.userInfo.followers_count;
    account.followingCount = data.userInfo.friends_count;
    account.statusesCount = data.userInfo.statuses_count;
    return account;
  }
}
